package com.yuzi.service.BaseSer;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.yuzi.common.Constant;
import com.yuzi.controller.BaseCon.BaseController;
import com.yuzi.model.BaseMo.BaseModel;
import com.yuzi.model.systemMo.SysRole;
import com.yuzi.model.systemMo.SysUser;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unchecked")
public abstract class BaseService {
    protected BaseController controller;
    private static Map<Class<? extends BaseService>, BaseService> INSTANCE_MAP = new HashMap<Class<? extends BaseService>, BaseService>();

    public final static String uploadPath = PropKit.use("jConfig.properties").get("baseUploadPath");

    /**
     * 注入Model
     */
    public BaseService(){
        Field[] fields =this.getClass().getDeclaredFields();
        for (int i=0;i < fields.length; i++){
            Field field = fields[i];
            Class clazz = field.getType();
            if (Model.class.isAssignableFrom(clazz) && clazz!=Model.class){
                try {
                    field.setAccessible(true);
                    field.set(this,BaseModel.getInstance(clazz));
                }catch (IllegalAccessException e){
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 存取实例化的Service
     * @param clazz
     * @param controller
     * @param <Ser>
     * @return
     */
    public static <Ser extends BaseService> Ser getInstance(Class<Ser> clazz, BaseController controller){
        Ser service = (Ser) INSTANCE_MAP.get(clazz);
        if (service == null){
            try {
                service = clazz.newInstance();
                INSTANCE_MAP.put(clazz, service);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        service.controller = controller;
        return service;
    }

    public SysUser getCurrentUser(){
        return controller.getSessionAttr(Constant.SessionKey.userKey);
    }

    public SysRole getCurrentRole(){
        return controller.getSessionAttr(Constant.SessionKey.roleKey);
    }


    public final static Cache pvCache = Redis.use(Constant.RedisType.pvCacheName);

}
